package com.xiaojiezhu.shiro.spring.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @Author 朱小杰
 * 时间 2017-08-06 .23:16
 * 说明 ...
 */
@RequestMapping("/user")
@Controller
public class UserController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("userName") String userName,@RequestParam("password") String password){
        Subject subject = SecurityUtils.getSubject();
        String cryptPwd = DigestUtils.sha256Hex(password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName,cryptPwd);
        try {
            token.setRememberMe(true);
            subject.login(token);
            return "index";
        } catch (AuthenticationException e) {
            return "fail";
        }
    }

    @RequestMapping("/admin")
    public String admin(HttpSession httpSession){
        //httpSession.setAttribute("a","哈哈");\
        System.out.println(httpSession.getAttribute("a"));
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        System.out.println(session.getAttribute("a"));

        System.out.println(httpSession.getClass().getName() + " == " + session.getClass().getName());
        return "admin";
    }

    @RequiresRoles("admin")
    @RequestMapping("/student")
    public String student(){
        return "admin" ;
    }

    @RequestMapping("/teacher")
    public String teacher(){
        return "admin" ;
    }

}
